<template>
  <div>
    <div class="search">
      <SearchVue :searchType="searchType" @getSearchData="getSearchData"></SearchVue>
    </div>
    <!-- <div class="headeButton">
      <el-button type="primary" @click="addFn">添加内容</el-button>
    </div> -->
    <div class="draggable" style="padding: 20px">
      <el-table row-key="id" :data="tableData" style="width: 100%">
        <template v-for="(item, index) in oldList" :key="`col_${index}`">
          <el-table-column
            v-if="item.type == 1"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 2"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-button type="primary" size="small" @click="detilsFn(scope.row)">详情</el-button>
                <el-button type="warning" size="small" @click="changeTableFn(scope.row)"
                  >修改</el-button
                >
                <el-popconfirm title="是否确认删除" @confirm="confirmDeleteFn(scope.row)">
                  <template #reference>
                    <el-button type="danger" size="small"> 删除 </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 3"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row.image" />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        :current-page="pageData.page"
        :page-size="pageData.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      @close="closeFn"
      v-model="dialogVisibleAdd"
      title="添加"
      width="500"
      :before-close="dialogBeforeCloseFn"
    >
      <div>
        <el-form
          ref="formAddRef"
          :rules="rules"
          :model="formAdd"
          label-width="auto"
          style="max-width: 800px"
        >
          <el-form-item label="产品类型：" prop="filmType">
            <el-input v-model="formAdd.filmType" class="imputeWidth" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="产品型号：" prop="filmName">
            <el-input v-model="formAdd.filmName" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="质保年限：" prop="filmAge">
            <el-input v-model="formAdd.filmAge" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="质保批号：" prop="filmNo">
            <el-input v-model="formAdd.filmNo" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="施工门店：" prop="storeWorkName">
            <el-input v-model="formAdd.storeWorkName" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="客户姓名：" prop="ownerName">
            <el-input v-model="formAdd.ownerName" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="客户电话：" prop="ownerPhone">
            <el-input v-model="formAdd.ownerPhone" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="车牌号：" prop="carNo">
            <el-input v-model="formAdd.carNo" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="车架号：" prop="carVIN">
            <el-input v-model="formAdd.carVIN" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="施工部位：" prop="carApart">
            <el-input v-model="formAdd.carApart" class="imputeWidth" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <div class="imagebOx">
              <div v-for="(item, index) in formAdd.imgList" :key="index" class="upBOx">
                <div v-if="!item.image" @click="upImgFn(item, index)">
                  <div class="upImg center">+</div>
                  <input
                    ref="inputFile"
                    type="file"
                    style="display: none"
                    @change="handleFileUpload"
                  />
                </div>
                <div v-else class="imgBox">
                  <img :src="item.image" alt="" />
                  <div class="Mask center">
                    <div @click="magnifyFn(item)">
                      <el-icon color="white"><Search /></el-icon>
                    </div>
                    <div @click="deleteImgFn(item)">
                      <el-icon color="red"><Delete /></el-icon>
                    </div>
                  </div>
                </div>
                <div class="imageBoxTitle">
                  {{ item.title }}
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="confirmFn(0)"> 确定 </el-button>
          <el-button @click="confirmFn(1)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-model="dialogVisibleDetils" title="详情" width="450">
      <div>
        <el-card class="card" v-if="detilsData.status == 2">
          <template #header>
            <div class="card-header">
              <span>驳回原因</span>
            </div>
          </template>
          <div>原因：{{ detilsData.reject }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>产品信息</span>
            </div>
          </template>
          <div>产品类型：{{ detilsData.filmType }}</div>
          <div>产品型号：{{ detilsData.filmName }}</div>
          <div>质保年限：{{ detilsData.filmAge }}</div>
          <div>质保批号：{{ detilsData.filmNo }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>门店信息</span>
            </div>
          </template>
          <div>施工门店：{{ detilsData.storeWorkName }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>车主信息</span>
            </div>
          </template>
          <div>姓名：{{ detilsData.ownerName }}</div>
          <div>电话：{{ detilsData.ownerPhone }}</div>
        </el-card>
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>车辆信息</span>
            </div>
          </template>
          <div>车牌号：{{ detilsData.carNo }}</div>
          <div>车架号：{{ detilsData.carVIN }}</div>
          <div>施工部位：{{ detilsData.carApart }}</div>
        </el-card>
        <el-card class="card">
          <div class="imageList">
            <div v-for="(item, index) in detilsData.imgList" :key="index" class="imageTitleBox">
              <div class="imageBox">
                <img :src="item.image" alt="" srcset="" />
              </div>
              <div class="imageTitle" style="text-align: center">
                {{ item.title }}
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="autionFn(1, detilsData)"> 审核通过 </el-button>
          <el-button @click="autionFn(2, detilsData)">驳回</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleImage">
      <div style="width: 100%; height: 100%">
        <img
          style="width: 100%; height: 100%"
          w-full
          :src="dialogVisibleImageUrl"
          alt="Preview Image"
        />
      </div>
    </el-dialog>
    <!-- 驳回原因 -->
    <el-dialog v-model="dialogVisibleRejct" width="480">
      <div>驳回原因： <el-input v-model="Rejct" type="textarea" placeholder="请输入" /></div>
      <div style="width: 100%; margin-top: 20px" class="center">
        <el-button type="primary" @click="RejctFn(1, detilsData)"> 确定 </el-button>
        <el-button @click="RejctFn(2, detilsData)">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup >
import { userListAdd, } from '@/http/api/users.js'
import { qualityList, qualitChange, qualitChangeStatus, qualitySerach, qualitDelete, uploadAvatar, qualitChangeStatusReject } from '@/http/api/store.js'
import { onMounted, reactive, ref, defineExpose } from 'vue'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import { baseURL } from '@/http/request.js'
import { ElMessage } from 'element-plus'
import SearchVue from '@/components/search/index.vue'
// 只适合做平级的table行和列拖动

let baseURL2 = baseURL
const oldList = ref()
const newList = ref()
// 表头
const tableItems = ref([
  {
    label: '客户姓',
    prop: 'ownerFirstName',
    type: 1
  }, {
    label: '客户名',
    prop: 'ownerLastName',
    type: 1
  },
  {
    label: '手机号',
    prop: 'ownerPhone',
    type: 1
  }, {
    label: '车型号',
    prop: 'carName',
    type: 1
  }, {
    label: '施工部位',
    prop: 'carApart',
    type: 1
  }, {
    label: '车架号',
    prop: 'carVIN',
    type: 1
  }, {
    label: '车牌号',
    prop: 'carNo',
    type: 1
  },
  {
    label: '质保批号',
    prop: 'filmNo',
    type: 1
  }, {
    label: '膜型号',
    prop: 'filmName',
    type: 1
  }, {
    label: '质保时间',
    prop: 'filmAge',
    type: 1
  }, {
    label: '审核状态',
    prop: 'statusSize',
    type: 1
  },
  {
    label: '操作',
    prop: 'age',
    type: 2
  },
])
// 表体数据
let tableData = ref([])
let searchType = ref([
  {
    title: '审核状态：',
    type: 3,
    model: 'status',
    hint: '请选择',
    options: [
      {
        label: '待审核',
        value: 0
      }, {
        label: '已审核',
        value: 1
      }, {
        label: '已驳回',
        value: 2
      },
    ]
  }, {
    title: '车主姓名：',
    type: 1,
    model: 'ownerName',
    hint: '请输入车主姓名'
  }, {
    title: '车主手机号：',
    type: 1,
    model: 'ownerPhone',
    hint: '请输入车主手机号'
  }, {
    title: '质保批号：',
    type: 1,
    model: 'filmNo',
    hint: '请输入质保批号'
  }, {
    title: '车牌号：',
    type: 1,
    model: 'carNo',
    hint: '请输入车牌号'
  },
])
let formAdd = reactive({})
let image = ref([])
let dialogVisibleImage = ref(false)
let pageData = reactive({
  page: 1,
  size: 10
})
const getData = async () => {
  let data = {
    ...pageData,
    status: [1, 2, 0],
  }
  const res = await qualityList(data)
  tableData.value = res.data.res.map((item) => {
    return {
      ...item,
      statusSize: item.status == '0' ? '待审核' : item.status == '1' ? '审核通过' : '已驳回'
    }
  })
  total.value = res.data.total
}
let dialogVisibleAdd = ref(false)
let total = ref(0)
const addFn = () => {
  dialogVisibleAdd.value = true
}
const closeFn = () => {
  dialogVisibleAdd.value = false
}

const rules = reactive({
  filmType: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  filmName: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  filmAge: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  filmNo: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  ownerName: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  ownerPhone: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  carVIN: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  carApart: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
})
// 上传成功
const handSuccessFn = (data) => {
  formAdd.avatar = data.image_url
}
let formAddRef = ref()
// 点击添加或这修改按钮
const confirmFn = async (number) => {
  if (number == 0) {
    await formAddRef.value.validate(async (valid, fields) => {
      console.log(valid)
      if (valid) {
        try {
          if (!formAdd.id) {
            await userListAdd(formAdd)
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            delete formAdd.statusSize
            delete formAdd.workTime
            await qualitChange(formAdd)
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
          }
          getData()


        } catch (error) {
          ElMessage({
            message: '失败',
            type: 'error',
          })
        }


      } else {
        ElMessage({
          message: '请补充完整信息',
          type: 'error',
        })
      }
    })
  }
  formAdd = reactive({})
  image.value = []
  dialogVisibleAdd.value = false
}
// 关闭弹窗
const dialogBeforeCloseFn = () => {
  formAdd = reactive({})
  image.value = []
  dialogVisibleAdd.value = false
}
// 修改size
const handleSizeChange = (data) => {
  pageData.size = data
  getData()
}
// 修改页数
const handleCurrentChange = (data) => {
  pageData.page = data
  getData()
}
// 确定删除
const confirmDeleteFn = async (data) => {
  try {
    const res = await qualitDelete({ id: data.id })
    ElMessage({
      message: res.data.message,
      type: 'success',
    })
    getData()
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }

}
// 修改
const changeTableFn = (data) => {
  dialogVisibleAdd.value = true
  data.imgList = JSON.parse(data.imgList)
  Object.assign(formAdd, data)
  console.log(formAdd)
  image.value = [{
    url: data.image,
    name: '11'
  }]
}
const getSearchData = async (data) => {
  let dataS = {
    ...data,
    ...pageData
  }
  let res = await qualitySerach(dataS)
  tableData.value = res.data.res.map((item) => {
    return {
      ...item,
    }
  })
  total.value = res.data.total
}
const handlePictureCardPreview = (data) => {
  dialogVisibleImage.value = true
}
let dialogVisibleDetils = ref(false)
let detilsData = reactive({})
// 查看详情
const detilsFn = (data) => {
  dialogVisibleDetils.value = true
  let detilsDataAll = JSON.parse(JSON.stringify(data))
  detilsDataAll.imgList = JSON.parse(data.imgList)
  Object.assign(detilsData, detilsDataAll)
  Rejct.value = data.reject
}
let dialogVisibleRejct = ref(false)
let Rejct = ref('')
// 审核通过
const autionFn = async (num, data) => {
  let res = reactive({})
  if (num == 2) {
    dialogVisibleRejct.value = true
  } else {
    res = await qualitChangeStatus({
      status: num,
      id: data.id
    })
    ElMessage({
      message: res.data.message,
      type: 'success',
    })
    dialogVisibleDetils.value = false
    getData()
  }


}
// 驳回
const RejctFn = async (num, data) => {
  if (num == 1) {
    const res = await qualitChangeStatusReject({
      status: 2,
      id: data.id,
      reject: Rejct.value
    })
    ElMessage({
      message: res.data.message,
      type: 'success',
    })

    getData()
  }
  Rejct.value = ''
  dialogVisibleRejct.value = false
  dialogVisibleDetils.value = false

}
let inputFile = ref(null)
// 上传图片
const upImgFn = (data, index) => {
  inputFile.value[0].addEventListener('change', async function (event) {
    var files = event.target.files[0]
    const formData = new FormData()
    //files 文件信息
    formData.append("uploadFiles", files)
    //提交的其他字段
    // 发送ajax请求
    const res = await uploadAvatar(formData)
    data.image = res.data.image_url
    console.log(data)

  })
  // 将input添加到文档中
  // document.body.appendChild(input);
  inputFile.value[0].click()
}
const deleteImgFn = (data) => {
  data.image = ''
}
let dialogVisibleImageUrl = ref('')
const magnifyFn = (data) => {
  console.log(data)
  dialogVisibleImage.value = true
  dialogVisibleImageUrl.value = data.image
}
onMounted(() => {
  oldList.value = JSON.parse(JSON.stringify(tableItems.value))
  newList.value = JSON.parse(JSON.stringify(tableItems.value))
  getData()
})
defineExpose({ getData })
</script>
<style lang="scss" scoped>
.imputeWidth {
  width: 260px;
}
.imageList {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.imageTitleBox {
  padding: 10px 0;
}
.imageBox {
  width: 134px;
  height: 135px;
  img {
    width: 100%;
    height: 100%;
  }
}
.imageTitle {
  width: 134px;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 使用省略号表示文本溢出 */
}
.card {
  margin-top: 20px;
}
.imagebOx {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.imageBoxTitle {
  width: 150px;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 使用省略号表示文本溢出 */
  text-align: center;
}
.upImg {
  background: #3c3c3c;
  width: 180px;
  height: 180px;
  border-radius: 20px;
  font-size: 50px;
  cursor: pointer;
}

.imgBox {
  width: 180px;
  height: 180px;
  border-radius: 20px;
  position: relative;
  left: 0;
  top: 0;
  img {
    width: 100%;
    height: 100%;
  }
  .Mask {
    flex-wrap: wrap;
    background: black;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    justify-content: space-around;
    font-size: 30px;
  }
  .Mask:hover {
    opacity: 0.6;
  }
  cursor: pointer;
}
</style>